﻿using Furion.TaskScheduler;
using Modules.ActionRun;
using Modules.MSentEvent;
using Prism.Events;
using Sorting.App.Models;
using Sorting.App.Models.Enum;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Lm.Core.Common.Util;
using Microsoft.Extensions.Caching.Memory;
using Modules.Units;
using Lm.Core.TaskQueue;
using Prism.Ioc;
using Prism.Mvvm;
using Furion.EventBus;
using Furion.DependencyInjection;
using log4net;
using Sorting.App.Services;
using Sorting.App.Models.Entity;
using System.Threading;
using System.Timers;
using Timer = System.Threading.Timer;

namespace Modules.Monitoring
{

    /// <summary>
    /// 监控帮助类
    /// </summary>
    public class MonitoringHeler
    {
        IContainerExtension _container;

        private ILog log = LogManager.GetLogger(typeof(MonitoringHeler));

        IEventAggregator _ea;
        private readonly TaskQueueHelper _taskQueueHelper;

        private ScanLogService scanLogService = new ScanLogService();
        public MonitoringHeler(IEventAggregator ea, IContainerExtension container, TaskQueueHelper taskQueueHelper)
        {
            _container = container;
            _ea = ea;
            _taskQueueHelper = taskQueueHelper;
        }


        /// <summary>
        /// 消息事件总线执行
        /// </summary>
        /// <param name="obj"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void SentEventExecute(MessageModel model)
        {
            switch (model.Code)
            {
                //看门狗启动、PLC存活、软件存活
                case EnumMessageType.ME301:
                    GetPlcLifeJob();
                    log.Info("看门狗启动、PLC存活、软件存活定时开启");
                    break;
                //激活软件信号监控线程
                case EnumMessageType.ME302:
                   //GetPlcStatus();
                    break;
                //激活输液袋入队信号监控
                case EnumMessageType.ME303:
                    GetHasInPoint();
                    //激活获取最后一袋的信号
                    GetLastInPoint();
                    break;
                //激活扫描队列
                case EnumMessageType.ME304:
                    StartScanThred();
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 停止PLC传感器信号监测
        /// </summary>

        public void StopGetPlcStatusJob()
        {
            SpareTime.Stop("GetPlcStatusJob");
        }

        private static Timer timerGetPlcLifeJob;
        private static Timer timerGetSoftWareLifeJob;
        private static Timer timerGetPlcStatus;
        private static Timer timerGetHasInPoint;
        private static Timer timerGetLastInPoint;
        private static Timer timerStartScanThred;

        /// <summary>
        /// GetPlcLifeJob
        /// 执行看门狗
        /// </summary>
        public void GetPlcLifeJob()
        {

            TimerCallback timeCB2 = new TimerCallback((object states) =>
            {
                //执行定时动作
                ActionRunHelper.GetSoftWareLifeCmd();
            });
            // Establish timer settings.
            timerGetSoftWareLifeJob = new Timer(
                timeCB2,             // The TimerCallback delegate type.
                "Hello From Main",  // Any info to pass into the called method (null for no info).
                0,                  // Amount of time to wait before starting.
                100);   //一秒钟调用一次 Interval of time between calls (in milliseconds).



            TimerCallback timeCB = new TimerCallback((object states) =>
            {
                //执行定时动作
                var res = ActionRunHelper.GetPlcLifeCmd();

                if (res != 1)
                {
                    //通知界面全局中断
                    _ea.GetEvent<ViewModelSentEvent>().Publish(new MessageModel
                    {
                        Code = EnumMessageType.ME102,
                        Message = "设备异常，全局中断",
                        Data = ""
                    });
                }
            });
            // Establish timer settings.
            timerGetPlcLifeJob = new Timer(
                timeCB,             // The TimerCallback delegate type.
                "Hello From Main",  // Any info to pass into the called method (null for no info).
                0,                  // Amount of time to wait before starting.
                100);   //一秒钟调用一次 Interval of time between calls (in milliseconds).
        }





        /// <summary>
        /// 获取PLC主要传感状态
        /// </summary>
        public void GetPlcStatus()
        {

            TimerCallback timeCB2 = new TimerCallback((object states) =>
             {
                 //执行定时动作
                 ActionRunHelper.StartMonitor();

                 //通知界面重新获取刷新
                 _ea.GetEvent<ViewModelSentEvent>().Publish(new MessageModel
                 {
                     Code = EnumMessageType.ME109,
                     Message = "通知传感器监控界面重新获取刷新",
                     Data = ""
                 });
             });
            // Establish timer settings.
            timerGetPlcStatus = new Timer(
                timeCB2,
                "Hello From Main",
                0,
                100);
        }


        /// <summary>
        /// 获取是否有输液袋入队信号
        /// </summary>
        public void GetHasInPoint()
        {

            TimerCallback timeCB2 = new TimerCallback(async (object states) =>
           {
               //执行定时动作
             // var a=await  ActionRunHelper.GetInLinePoint();
               var res = AppsettingUnits.SignalModel.InLinePoint;

               //有输液袋入队
               if (res)
               {
                   _ea.GetEvent<ViewModelSentEvent>().Publish(new MessageModel
                   {
                       Code = EnumMessageType.ME108,
                       Message = "放入",
                       Data = ""
                   });
                   AppsettingUnits.SignalModel.InLinePoint = false;

               }
           } );
            // Establish timer settings.
            timerGetHasInPoint = new Timer(
                timeCB2,
                "Hello From Main",
                0,
                100);


        }


        /// <summary>
        /// 获取最后一袋入队信号
        /// </summary>
        public void GetLastInPoint()
        {


            TimerCallback timeCB2 = new TimerCallback((object states) =>
           {
               //执行定时动作
           //    ActionRunHelper.GetEndDrugPoint();
               var res = AppsettingUnits.SignalModel.EndDrugPoint;
               if (res)
               {
                   if (TaskQueueHelper.PutDrugTask.TaskCount >= 1 && string.IsNullOrEmpty(AppsettingUnits.ScanInfo))
                   {
                       var DefaultNo = AppsettingUnits.Appseeting.DefaultNo;
                       var task = TaskQueueHelper.PutDrugTask.Peek();
                       _ea.GetEvent<ViewModelSentEvent>().Publish(new MessageModel
                       {
                           Code = EnumMessageType.ME104,
                           Data = DefaultNo.ToString().Trim(),
                           Message = $"扫描信息【{DefaultNo}】"
                       });

                       TaskQueueHelper.PutDrugTask.Dequeue();
                   }
               }
           });
            // Establish timer settings.
            timerGetLastInPoint = new Timer(
                timeCB2,
                "Hello From Main",
                0,
                100);

        }




        /// <summary>
        /// 执行扫描
        /// </summary>
        public void StartScanThred()
        {


            TimerCallback timeCB2 = new TimerCallback((object states) =>
           {
               var msg = ScanActionHelper.SerialRead();
               if (!string.IsNullOrEmpty(msg))
               {
                   AppsettingUnits.ScanInfo=msg.Trim();

                   //var scandto = new ScanLogDto();
                   //scandto.msg = msg.Trim();
                   //scandto.createtime = DateTime.Now.ToString();

                   ////调用新增扫描日志
                   //scanLogService.PostScanLog(scandto);


               }
           });
            // Establish timer settings.
            timerStartScanThred = new Timer(
                timeCB2,
                "Hello From Main",
                0,
                100);
        }

        /// <summary>
        /// 停止所有任务
        /// </summary>
        public void StopAllTimer()
        {
            timerGetPlcLifeJob.Dispose();
            timerGetSoftWareLifeJob.Dispose();
            timerStartScanThred.Dispose();
            timerGetHasInPoint.Dispose();
            timerGetLastInPoint.Dispose();

        }
    }
}
